package com.hc.weather.service;

import com.hc.weather.domain.WeatherResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
/*
* 对天气业务的服务
* */
@Service
public class WeatherService {

    @Autowired
    RestTemplate restTemplate;
    @Autowired
    RedisTemplate redisTemplate;

//    1.抓取天气数据的方法
    public WeatherResponse fetchWeatherData(String cityid){

        //json字符串,而我们需要的是Java对象
        //所以,需要json字符串反序列化成Java对象
        WeatherResponse result =  restTemplate.getForObject("https://apis.tianapi.com/tianqi/index?key=2af8ed08605c20f76f8183d1b702474b&city="+cityid+"&type=7",WeatherResponse.class);
        return result;
    }

    /**
     * 2.查询天气数据的方法，处理用户请求时使用该方法
     */
    public WeatherResponse queryWeatherForUser(String cityId){
        WeatherResponse weatherResponse=null;

        //1.查询缓存
        weatherResponse=(WeatherResponse)redisTemplate.opsForHash().get("hechi_weather_data",cityId);

        if(weatherResponse==null){
            System.out.println("缓存中没有天气数据============================================================");
            //2.查询第三方接口
            weatherResponse=fetchWeatherData(cityId);
        }
        return weatherResponse;
    }
}
